/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package koor.action.user;

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import koor.action.Action;
import koor.action.ActionResult;
import koor.entity.Role;
import koor.entity.Teacher;
import koor.entity.User;
import koor.persistent.RoleDAO;
import koor.persistent.TeacherDAO;
import koor.persistent.UserDAO;
import koor.service.ServiceLocator;

/**
 * The
 * <code>UserSaveAction</code> class represents admin action, used to save
 * user information
 *
 * @author Admin
 */
public class UserSaveAction implements Action {

    @Override
    public String getName() {
        return "user.save";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {

        // if Save button have been pressed
        if (request.getParameter("saveButton") != null) {
            UserDAO userDAO = ServiceLocator.getService(UserDAO.class);

            User user = new User();

            // load data from request
            if (request.getParameter("login") != null) {
                user.setLogin(request.getParameter("login"));
            }

            if (request.getParameter("password") != null) {
                user.setPassword(request.getParameter("password"));
            }

            if (request.getParameter("role") != null) {
                RoleDAO roleDAO = ServiceLocator.getService(RoleDAO.class);
                Role role = roleDAO.findOne(Long.parseLong(request.getParameter("role")));
                user.setRole(role);
            }
            
            if (request.getParameter("person") != null) {
                TeacherDAO teacherDAO = ServiceLocator.getService(TeacherDAO.class);
                Teacher teacher = teacherDAO.findOne(Long.parseLong(request.getParameter("person")));
                user.setPerson(teacher);
            }
            try {
                userDAO.save(user);
                request.getSession().setAttribute("win", "Пользователь добавлен");
            } catch (Exception e) {
                request.getSession().setAttribute("fail", "Не удалось добавить пользователя");
                return ActionResult.redirect("user.create");
            }
        }
        return ActionResult.redirect("user.list");
    }
}
